package avicit.bdp.dms.tdm.service;


import avicit.bdp.common.base.BaseService;
import avicit.bdp.common.utils.BdpLogUtil;
import avicit.bdp.common.utils.redis.RedisCacheHelper;
import avicit.bdp.core.constant.Constants;
import avicit.bdp.core.util.json.JSONUtils;
import avicit.bdp.dms.tdm.dao.AppClientDAO;
import avicit.bdp.dms.tdm.dto.AppClientDTO;
import avicit.bdp.dms.tdm.utils.TdmConstants;
import avicit.platform6.api.system.ConvertColumnClient;
import avicit.platform6.api.system.impl.SystemConstant;
import avicit.platform6.commons.utils.BusinessUtil;
import avicit.platform6.core.properties.PlatformConstant;
import avicit.platform6.core.rest.msg.QueryRespBean;
import avicit.platform6.modules.system.syslog.service.SysLogUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * 我的应用表服务
 */
@Transactional
@Service
public class AppClientService extends BaseService<AppClientDAO, AppClientDTO> {

    public static final String CLIENT_CREDENTIALS = "client_credentials";

    public static final String EASY_CREDENTIALS = "easy_credentials";

    @Autowired
    private ConvertColumnClient convertColumnClient;

    @Autowired
    private RedisCacheHelper redisCacheHelper;

    public void save(AppClientDTO dto) {
        if (StringUtils.isNotBlank(dto.getClientId())) {
            AppClientDTO old = this.selectByPrimaryKey(dto.getClientId());
            old.setClientName(dto.getClientName());
            old.setDescription(dto.getDescription());
            if (!dto.getGrantTypes().equals(old.getGrantTypes())) {
                if (CLIENT_CREDENTIALS.equals(dto.getGrantTypes())) {
                    String clientSecret = RandomStringUtils.random(16, true, true);
                    old.setClientSecret(clientSecret);
                    old.setAccessTokenValidity(dto.getAccessTokenValidity());
                    old.setRefreshTokenValidity(dto.getRefreshTokenValidity());
                } else {
                    old.setClientSecret(null);
                    old.setAccessTokenValidity(null);
                    old.setRefreshTokenValidity(null);
                }
            }
            old.setGrantTypes(dto.getGrantTypes());
            this.updateByPrimaryKey(old);
            SysLogUtil.log4Update(dto, old);
        } else {
            dto.setClientId(RandomStringUtils.random(20, true, true));
            if (CLIENT_CREDENTIALS.equals(dto.getGrantTypes())) {
                String clientSecret = RandomStringUtils.random(16, true, true);
                dto.setClientSecret(clientSecret);
                dto.setAccessTokenValidity(dto.getAccessTokenValidity());
                dto.setRefreshTokenValidity(dto.getRefreshTokenValidity());
            }
            dto.setArchived(0);
            this.insert(dto);

            //添加到redis
            redisCacheHelper.set(TdmConstants.ASSET_APP_CLIENT + dto.getClientId(),
                    JSONUtils.toJsonString(dto));
            // 记录日志
            SysLogUtil.log4Insert(dto);
        }
    }

    public QueryRespBean<AppClientDTO> getAppClientPageList(String keyWords, Integer pageNo, Integer pageSize) {
        QueryRespBean<AppClientDTO> queryRespBean = new QueryRespBean<>();
        PageHelper.startPage(pageNo, pageSize);

        Page<AppClientDTO> page = this.mapper.getAppClientPageList(keyWords);
        try {
            valueConvert(page);
        } catch (Exception e) {
            e.printStackTrace();
        }
        queryRespBean.setResult(page);
        BdpLogUtil.log4Query(queryRespBean);
        return queryRespBean;

    }

    private void valueConvert(Page<AppClientDTO> page) {
        //循环组装请求数据
        Map<String, Set<String>> convertFormData = new HashMap<>(16);
        for (AppClientDTO appClientDTO : page) {
            BusinessUtil.createConvertSet(convertFormData, SystemConstant.USER, appClientDTO.getCreatedBy());
            BusinessUtil.createConvertSet(convertFormData, avicit.bdp.core.constant.Constants.BDP_DATA_SECRET_LEVEL_KEY, appClientDTO.getSecretLevel());
        }
        if (convertFormData.size() > 0) {
            //获取请求结果
            Map<String, Map<String, String>> convertResultData = convertColumnClient.replace(convertFormData);
            //循环设置Alias或Name的值
            for (AppClientDTO appClientDTO : page) {
                appClientDTO.setCreatedBy(BusinessUtil.convertFormat(convertResultData, SystemConstant.USER, appClientDTO.getCreatedBy()));
                appClientDTO.setSecretLevelName(BusinessUtil.convertFormat(convertResultData, Constants.BDP_DATA_SECRET_LEVEL_KEY, appClientDTO.getSecretLevel()));
            }
        }
    }

    public void deleteApp(AppClientDTO dto) {
        AppClientDTO appClientDTO = new AppClientDTO();
        appClientDTO.setClientId(dto.getClientId());
        appClientDTO.setArchived(1);
        this.updateByPrimaryKeySelective(appClientDTO);
        //从redis删除
        redisCacheHelper.del(TdmConstants.ASSET_APP_CLIENT + dto.getClientId());

        String logTitle = "删除我的应用：【" + dto.getClientId() + "】";
        BdpLogUtil.log("数据资产-我的应用模块", logTitle, PlatformConstant.OpType.delete);
    }

    public AppClientDTO getAppClientByClientId(String clientId) {
        return this.mapper.getAppClientByClientId(clientId);
    }

    public List<AppClientDTO> getAppClientList() {
        return this.mapper.getAppClientList();
    }
}
